package com.wits.platform.service;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wits.platform.common.exception.I18nServiceException;
import com.wits.platform.common.utils.StringUtil;
import com.wits.platform.dao.MenuDao;
import com.wits.platform.dao.MmrRoleMenuDao;
import com.wits.platform.dao.ResourceDao;
import com.wits.platform.dto.MenuDTO;
import com.wits.platform.dto.ResourceDTO;
import com.wits.platform.entity.Menu;
import com.wits.platform.entity.Role;

@Component
public class MenuService extends BaseService<Menu,String>{


	private MenuDao menuDao;

	@Autowired
	private MmrRoleMenuDao mmrRoleMenuDao;
	
	@Autowired
	private ResourceDao resourceDao;


	@Autowired
	public void setMenuDao(MenuDao menuDao) {
		this.baseDao=menuDao;
		this.menuDao = menuDao;
	}

	public void deleteInBatch(String ids) {
		String decoratorIds=StringUtil.decorator("'",StringUtil.split(ids, ","));
		int childrenCount=menuDao.findChildrenCountByPIds(decoratorIds);
		if(childrenCount>0){
			throw new I18nServiceException("menu_del_foreign_rel_self");
		}
		List<Menu> menuList=this.findAll(Arrays.asList(StringUtil.split(ids,",")));
		List<Role> roles=null;
		for(Menu menu : menuList){
			roles=menu.getRoles();
			for(Role role : roles){
				role.removeMenu(menu);
			}
		}
		menuDao.delete(menuList);
	}

	
	public List<Menu> findByMuName(String muName) {
		return menuDao.findByMuName(muName);
	}

	public List<Menu> findByMuHref(String muHref) {
		return menuDao.findByMuHref(muHref);
	}

	public List<Menu> findByMuRel(String muRel) {
		return menuDao.findByMuRel(muRel);
	}

	/**
	 * 
	 * @param userId
	 * @return
	 */
	public List<Menu> findMenuByUserId(String userId) {
		return menuDao.findMenuByUserId(userId);
	}

	public String getRightTree(String roleId) {
		List<MenuDTO> menuList=null;
		List<ResourceDTO> rList=null;
		if(StringUtils.isNotEmpty(roleId)){
			menuList=menuDao.findMenuForRole(roleId);
			rList=resourceDao.findResourceForRole(roleId);
		}else{
			menuList=menuDao.findMenuForRole();
			rList=resourceDao.findResourceForRole();
		}
		StringBuilder str=new StringBuilder();
		str.append("[");
		for(MenuDTO m:menuList){
			str.append(m.toRightTree()).append(",");
		}
		
		ResourceDTO resource=null;
		int len=rList.size();
		for(int i=0;i<len;i++){
			resource=rList.get(i);
			str.append(resource.toRightTree());
			if(i+1<len){
				str.append(",");
			}
		}
		str.append("]");
		return str.toString();
	}






}
